package cc.magicjson.example.demo.threadlocal.concurrent;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import static java.lang.Boolean.TRUE;

/**
 * {@link}
 *
 * @author <a href="mailto:it_magicjson@163.com">MagicJson</a>
 * @since 1.0.0
 */
@Configuration
public class GlobalThreadPool {

	private static final int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;

	private static final int maxPoolSize = (Runtime.getRuntime().availableProcessors()) << 1 + 1;

	private static final int keepAliveTime = 60;

	private static final int queueCapacity = 2048;

	@Bean
	public Executor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);
		executor.setMaxPoolSize(maxPoolSize);
		executor.setKeepAliveSeconds(keepAliveTime);
		executor.setQueueCapacity(queueCapacity);
		executor.setThreadNamePrefix("task-executor-");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		executor.setDaemon(TRUE);
		executor.setTaskDecorator(new UserTaskDecorator());
		executor.initialize();

		return TtlExecutors.getTtlExecutor(executor);
	}


}
